package com.ruoyi.web.cp.service.ob;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import com.ruoyi.web.cp.domain.rm.ObGame;
import com.ruoyi.web.cp.service.WinxinService;
import com.ruoyi.web.cp.service.http.ObHttpService;
import com.ruoyi.web.mapper.ObGameMapper;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class ObGameService {
    @Autowired
    private ObGameMapper obGameMapper;
    @Autowired
    private ObHttpService obHttpService;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private ConfigLoader configLoader;

    public void saveObGames(List<ObGame> games) {
        Date date = new Date();
        List<String> gameIds = obGameMapper.selectByDateRange2(DateUtil.offsetDay(date, -2),
                DateUtil.offsetDay(date, 2));
        for (int i = 0; i < games.size(); i++) {
            ObGame obGame = games.get(i);
            if (!gameIds.contains(obGame.getGameId())) {
                obGameMapper.insert(obGame);
            }
        }
    }

    @Transactional
    public void saveByGameId(ObGame entity) {
        if (entity == null) {
            return;
        }
        // 1. 查询是否已存在记录
        ObGame obGame = obGameMapper.selectByGameId(entity.getGameId());
        // 2. 如果存在，设置其 ID 以便更新

        if (obGame == null) {
            entity.setId(obGame.getId());
            obGameMapper.updateById(entity);
        }
    }


    public void saveObGameResult() {
        Date date = new Date();
        DateTime dateTime = DateUtil.offsetDay(date, -2);
        dateTime = DateUtil.beginOfDay(dateTime);

        JSONObject data = obHttpService.sendObGameLeague(dateTime.getTime(), date.getTime());
        if (CollUtil.isEmpty(data)) {
            return;
        }
        if (CollUtil.isEmpty(data.getJSONArray("data"))) {
            return;
        }
        JSONArray datas = data.getJSONArray("data");
        List<String> leagueIds = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            JSONObject item = datas.getJSONObject(i);
            leagueIds.add(item.getString("id"));
        }

        data = obHttpService.sendObGameResult(dateTime.getTime(), date.getTime(), 1, leagueIds);
        if (CollUtil.isEmpty(data)) {
            return;
        }
        if (CollUtil.isEmpty(data = data.getJSONObject("data"))) {
            return;
        }
        List<String> emptyGameIds = obGameMapper.selectEmptyScoresGameIds();
        saveObGameResult(data.getJSONArray("records"), emptyGameIds);
        int pages = data.getIntValue("pages");
        for (int i = 1; i < pages; i++) {
            data = obHttpService.sendObGameResult(dateTime.getTime(), date.getTime(), 1 + i, leagueIds);
            if (CollUtil.isEmpty(data)) {
                continue;
            }
            if (CollUtil.isEmpty(data = data.getJSONObject("data"))) {
                continue;
            }
            saveObGameResult(data.getJSONArray("records"), emptyGameIds);
        }
    }

    private void saveObGameResult(JSONArray records, List<String> emptyGameIds) {
        for (int i = 0; i < records.size(); i++) {
            JSONObject record = records.getJSONObject(i);
            ObGame obGame = new ObGame();
            String gameId = record.getString("matchId");
            if (!emptyGameIds.contains(gameId)) {
                continue;
            }
            obGame.setGameId(gameId);
            JSONArray scoreResults = record.getJSONArray("scoreResult");
            for (int j = 0; j < scoreResults.size(); j++) {
                String score = scoreResults.getString(j);
                String[] scores = score.split("\\|");
                if ("S2".equals(scores[0])) {
                    obGame.setHalfScore(String.valueOf(scores[1]));
                }
                if ("S1".equals(scores[0])) {
                    obGame.setAllScore(String.valueOf(scores[1]));
                }
            }
            obGameMapper.updateByPrimaryKeySelective(obGame);
        }
    }


    public void sendObGameResult(String days, String key) {
        DateTime date = DateUtil.offsetDay(new Date(), -1 * Integer.parseInt(days));
        List<ObGame> obGames = obGameMapper.selectByDateRange3(date);
        String path = configLoader.getRmPath() + "OB上下半场全胜.xlsx";
        String path2 = configLoader.getRmPath() + "OB上下半场全胜-未比.xlsx";
        File tempFile = new File(path);
        // 如果文件已存在，先删除
        if (tempFile.exists()) {
            FileUtil.del(tempFile);
        }
        File tempFile2 = new File(path2);
        // 如果文件已存在，先删除
        if (tempFile2.exists()) {
            FileUtil.del(tempFile2);
        }
        // 导出到 Excel
        exportRmobDoubleMergeToExcel(obGames, tempFile, tempFile2);
        winxinService.sendQlMedia(key, path);
        winxinService.sendQlMedia(key, path2);
    }

    public void exportRmobDoubleMergeToExcel(List<ObGame> ObGameList, File tempFile, File tempFile2) {
        // 创建 ExcelWriter 对象
        ExcelWriter writer = ExcelUtil.getWriter(tempFile);
        ExcelWriter writer2 = ExcelUtil.getWriter(tempFile2);

        // 手动设置表头
        String[] headers = {"日期", "联赛", "主队", "客队",
                "亚盘",
                "上下半场全胜-主", "红黑",
                "上下半场全胜-客", "红黑",
//                "上半场零失球获胜-主", "红黑",
//                "下半场零失球获胜-客", "红黑",
//                "下半场零失球获胜-主", "红黑",
//                "下半场零失球获胜-客", "红黑",
                "全场零失球获胜-主", "红黑",
                "全场零失球获胜-客", "红黑",
                "全场零失球-主", "红黑",
                "全场零失球-客", "红黑",
                "上下半场均进球-主", "红黑",
                "上下半场均进球-客", "红黑",
                "半场结果", "全场结果"};
        writer.writeHeadRow(Arrays.asList(headers));
        writer2.writeHeadRow(Arrays.asList(headers));

        // 写入数据（假设 RmobDoubleMerge 有对应的 getter 方法）
        for (ObGame item : ObGameList) {
            String halfScore = item.getHalfScore();
            String allScore = item.getAllScore();
            Date date = item.getDate();
            String dateStr = DateUtil.format(date, "yyyy-MM-dd HH:mm");

            JSONObject details = null;
            if (item.getDetails() == null) {
                details = new JSONObject();
            } else {
                details = JSONObject.parseObject(item.getDetails());
            }
            Boolean sx_all_win_plv_teamA_boo = null,
                    sx_all_win_plv_teamB_boo = null,
                    s_ling_win_plv_teamA_boo = null,
                    s_ling_win_plv_teamB_boo = null,
                    x_ling_win_plv_teamA_boo = null,
                    x_ling_win_plv_teamB_boo = null,
                    sx_ling_win_plv_teamA_boo = null,
                    sx_ling_win_plv_teamB_boo = null,
                    all_ling_plv_teamA_boo = null,
                    all_ling_plv_teamB_boo = null,
                    sx_have_goal_plv_teamA_boo = null,
                    sx_have_goal_plv_teamB_boo = null;

            Double sx_all_win_plv_teamA = details.getDouble("sx_all_win_plv_teamA"),
                    sx_all_win_plv_teamB = details.getDouble("sx_all_win_plv_teamB"),
                    s_ling_win_plv_teamA = details.getDouble("s_ling_win_plv_teamA"),
                    s_ling_win_plv_teamB = details.getDouble("s_ling_win_plv_teamB"),
                    x_ling_win_plv_teamA = details.getDouble("x_ling_win_plv_teamA"),
                    x_ling_win_plv_teamB = details.getDouble("x_ling_win_plv_teamB"),
                    sx_ling_win_plv_teamA = details.getDouble("sx_ling_win_plv_teamA"),
                    sx_ling_win_plv_teamB = details.getDouble("sx_ling_win_plv_teamB"),
                    all_ling_plv_teamA = details.getDouble("all_ling_plv_teamA"),
                    all_ling_plv_teamB = details.getDouble("all_ling_plv_teamB"),
                    sx_have_goal_plv_teamA = details.getDouble("sx_have_goal_plv_teamA"),
                    sx_have_goal_plv_teamB = details.getDouble("sx_have_goal_plv_teamB");
            {
                if (sx_all_win_plv_teamA != null && sx_all_win_plv_teamA > 1.1) {
                    sx_all_win_plv_teamA = null;
                }
                if (sx_all_win_plv_teamB != null && sx_all_win_plv_teamB > 1.1) {
                    sx_all_win_plv_teamB = null;
                }
                if (s_ling_win_plv_teamA != null && s_ling_win_plv_teamA > 1.1) {
                    s_ling_win_plv_teamA = null;
                }
                if (s_ling_win_plv_teamB != null && s_ling_win_plv_teamB > 1.1) {
                    s_ling_win_plv_teamB = null;
                }
                if (x_ling_win_plv_teamA != null && x_ling_win_plv_teamA > 1.1) {
                    x_ling_win_plv_teamA = null;
                }
                if (x_ling_win_plv_teamB != null && x_ling_win_plv_teamB > 1.1) {
                    x_ling_win_plv_teamB = null;
                }
                if (sx_ling_win_plv_teamA != null && sx_ling_win_plv_teamA > 1.1) {
                    sx_ling_win_plv_teamA = null;
                }
                if (sx_ling_win_plv_teamB != null && sx_ling_win_plv_teamB > 1.1) {
                    sx_ling_win_plv_teamB = null;
                }
                if (all_ling_plv_teamA != null && all_ling_plv_teamA > 1.1) {
                    all_ling_plv_teamA = null;
                }
                if (all_ling_plv_teamB != null && all_ling_plv_teamB > 1.1) {
                    all_ling_plv_teamB = null;
                }
                if (sx_have_goal_plv_teamA != null && sx_have_goal_plv_teamA > 1.1) {
                    sx_have_goal_plv_teamA = null;
                }
                if (sx_have_goal_plv_teamB != null && sx_have_goal_plv_teamB > 1.1) {
                    sx_have_goal_plv_teamB = null;
                }
            }
            if (halfScore != null && allScore != null) {
                int[] halfScores = Arrays.stream(halfScore.split(":")).mapToInt(Integer::parseInt).toArray();
                int[] allScores = Arrays.stream(allScore.split(":")).mapToInt(Integer::parseInt).toArray();
                //上下半场全胜-主
                if (sx_all_win_plv_teamA != null) {
                    sx_all_win_plv_teamA_boo = halfScores[0] > halfScores[1]
                            && (allScores[0] - halfScores[0]) > (allScores[1] - halfScores[1]);
                }
                //上下半场全胜-客
                if (sx_all_win_plv_teamB != null) {
                    sx_all_win_plv_teamB_boo = halfScores[0] < halfScores[1]
                            && (allScores[0] - halfScores[0]) < (allScores[1] - halfScores[1]);
                }
                //上半场零失球获胜-主
                if (s_ling_win_plv_teamA != null) {
                    s_ling_win_plv_teamA_boo = halfScores[0] > halfScores[1]
                            && halfScores[1] == 0;
                }
                //上半场零失球获胜-客
                if (s_ling_win_plv_teamB != null) {
                    s_ling_win_plv_teamB_boo = halfScores[0] < halfScores[1]
                            && halfScores[0] == 0;
                }
                //下半场零失球获胜-主
                if (x_ling_win_plv_teamA != null) {
                    x_ling_win_plv_teamA_boo = (allScores[0] - halfScores[0]) > (allScores[1] - halfScores[1])
                            && (allScores[1] - halfScores[1]) == 0;
                }
                //下半场零失球获胜-客
                if (x_ling_win_plv_teamB != null) {
                    x_ling_win_plv_teamB_boo = (allScores[0] - halfScores[0]) < (allScores[1] - halfScores[1])
                            && (allScores[0] - halfScores[0]) == 0;
                }
                //全场零失球获胜-主
                if (sx_ling_win_plv_teamA != null) {
                    sx_ling_win_plv_teamA_boo = allScores[0] > allScores[1]
                            && allScores[1] == 0;
                }
                //全场零失球获胜-客
                if (sx_ling_win_plv_teamB != null) {
                    sx_ling_win_plv_teamB_boo = allScores[0] < allScores[1]
                            && allScores[0] == 0;
                }
                //全场零失球-主
                if (all_ling_plv_teamA != null) {
                    all_ling_plv_teamA_boo = allScores[1] == 0;
                }
                //全场零失球-客
                if (all_ling_plv_teamB != null) {
                    all_ling_plv_teamB_boo = allScores[0] == 0;
                }
                //上下半场均进球-主
                if (sx_have_goal_plv_teamA != null) {
                    sx_have_goal_plv_teamA_boo = halfScores[0] >= 1
                            && allScores[0] > halfScores[0];
                }
                //上下半场均进球-客
                if (sx_have_goal_plv_teamB != null) {
                    sx_have_goal_plv_teamB_boo = halfScores[1] >= 1
                            && allScores[1] > halfScores[1];
                }
            }

            writer.writeRow(Arrays.asList(
                    dateStr,            // 日期
                    item.getLeague(),          // 联赛
                    item.getTeamA(),           // 主队
                    item.getTeamB(),           // 客队
                    details.getString("asian_desc"),           // 亚盘
                    sx_all_win_plv_teamA,          // 上下半场全胜-主
                    sx_all_win_plv_teamA_boo == null ? "" : (sx_all_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
                    sx_all_win_plv_teamB,      // 上下半场全胜-客
                    sx_all_win_plv_teamB_boo == null ? "" : (sx_all_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
//                    s_ling_win_plv_teamA,        // 上半场零失球获胜-主
//                    s_ling_win_plv_teamA_boo == null ? "" : (s_ling_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
//                    s_ling_win_plv_teamB,        // 上半场零失球获胜-客
//                    s_ling_win_plv_teamB_boo == null ? "" : (s_ling_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
//                    x_ling_win_plv_teamA,        // 下半场零失球获胜-主
//                    x_ling_win_plv_teamA_boo == null ? "" : (x_ling_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
//                    x_ling_win_plv_teamB,        // 下半场零失球获胜-客
//                    x_ling_win_plv_teamB_boo == null ? "" : (x_ling_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
                    sx_ling_win_plv_teamA,        // 全场零失球获胜-主
                    sx_ling_win_plv_teamA_boo == null ? "" : (sx_ling_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
                    sx_ling_win_plv_teamB,        // 全场零失球获胜-客
                    sx_ling_win_plv_teamB_boo == null ? "" : (sx_ling_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
                    all_ling_plv_teamA,        // 全场零失球-主
                    all_ling_plv_teamA_boo == null ? "" : (all_ling_plv_teamA_boo ? "黑" : "红"),        // 红黑
                    all_ling_plv_teamB,        // 全场零失球-客
                    all_ling_plv_teamB_boo == null ? "" : (all_ling_plv_teamB_boo ? "黑" : "红"),        // 红黑
                    sx_have_goal_plv_teamA,        // 上下半场均进球-主
                    sx_have_goal_plv_teamA_boo == null ? "" : (sx_have_goal_plv_teamA_boo ? "黑" : "红"),        // 红黑
                    sx_have_goal_plv_teamB,        // 上下半场均进球-客
                    sx_have_goal_plv_teamB_boo == null ? "" : (sx_have_goal_plv_teamB_boo ? "黑" : "红"),        // 红黑
                    halfScore,          // 半场结果
                    allScore            // 全场结果
            ));
            if (item.getDate().getTime() > System.currentTimeMillis()) {
                writer2.writeRow(Arrays.asList(
                        dateStr,            // 日期
                        item.getLeague(),          // 联赛
                        item.getTeamA(),           // 主队
                        item.getTeamB(),           // 客队
                        details.getString("asian_desc"),           // 亚盘
                        sx_all_win_plv_teamA,          // 上下半场全胜-主
                        sx_all_win_plv_teamA_boo == null ? "" : (sx_all_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
                        sx_all_win_plv_teamB,      // 上下半场全胜-客
                        sx_all_win_plv_teamB_boo == null ? "" : (sx_all_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
//                        s_ling_win_plv_teamA,        // 上半场零失球获胜-主
//                        s_ling_win_plv_teamA_boo == null ? "" : (s_ling_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
//                        s_ling_win_plv_teamB,        // 上半场零失球获胜-客
//                        s_ling_win_plv_teamB_boo == null ? "" : (s_ling_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
//                        x_ling_win_plv_teamA,        // 下半场零失球获胜-主
//                        x_ling_win_plv_teamA_boo == null ? "" : (x_ling_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
//                        x_ling_win_plv_teamB,        // 下半场零失球获胜-客
//                        x_ling_win_plv_teamB_boo == null ? "" : (x_ling_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
                        sx_ling_win_plv_teamA,        // 全场零失球获胜-主
                        sx_ling_win_plv_teamA_boo == null ? "" : (sx_ling_win_plv_teamA_boo ? "黑" : "红"),        // 红黑
                        sx_ling_win_plv_teamB,        // 全场零失球获胜-客
                        sx_ling_win_plv_teamB_boo == null ? "" : (sx_ling_win_plv_teamB_boo ? "黑" : "红"),        // 红黑
                        all_ling_plv_teamA,        // 全场零失球-主
                        all_ling_plv_teamA_boo == null ? "" : (all_ling_plv_teamA_boo ? "黑" : "红"),        // 红黑
                        all_ling_plv_teamB,        // 全场零失球-客
                        all_ling_plv_teamB_boo == null ? "" : (all_ling_plv_teamB_boo ? "黑" : "红"),        // 红黑
                        sx_have_goal_plv_teamA,        // 上下半场均进球-主
                        sx_have_goal_plv_teamA_boo == null ? "" : (sx_have_goal_plv_teamA_boo ? "黑" : "红"),        // 红黑
                        sx_have_goal_plv_teamB,        // 上下半场均进球-客
                        sx_have_goal_plv_teamB_boo == null ? "" : (sx_have_goal_plv_teamB_boo ? "黑" : "红"),        // 红黑
                        halfScore,          // 半场结果
                        allScore            // 全场结果
                ));
            }
        }
        int[] columnWidths = {
                18 * 256, // 日期
                20 * 256, // 联赛
                22 * 256, // 主队
                22 * 256, // 客队
                8 * 256,  // 亚盘
                18 * 256, // 上下半场全胜-主
                8 * 256, // 红黑
                18 * 256, // 上下半场全胜-客
                8 * 256, // 红黑
//                18 * 256, // 上半场零失球获胜-主
//                8 * 256, // 红黑
//                18 * 256, // 上半场零失球获胜-客
//                8 * 256, // 红黑
//                18 * 256, // 下半场零失球获胜-主
//                8 * 256, // 红黑
//                18 * 256, // 下半场零失球获胜-客
//                8 * 256, // 红黑
                18 * 256, // 全场零失球获胜-主
                7 * 256, // 红黑
                18 * 256, // 全场零失球获胜-客
                7 * 256, // 红黑
                18 * 256, // 全场零失球-主
                7 * 256, // 红黑
                18 * 256, // 全场零失球-客
                7 * 256, // 红黑
                18 * 256, // 上下半场均进球-主
                7 * 256, // 红黑
                18 * 256, // 上下半场均进球-客
                7 * 256, // 红黑
                8 * 256,  // 半场结果
                8 * 256,  // 全场结果
        };

        for (int i = 0; i < columnWidths.length; i++) {
            writer.getSheet().setColumnWidth(i, columnWidths[i]);
        }
        for (int i = 0; i < columnWidths.length; i++) {
            writer2.getSheet().setColumnWidth(i, columnWidths[i]);
        }

        // 在writer.close()之前添加条件格式
        // 当单元格值为"黑"时，设置红色字体
        Sheet sheet = writer.getSheet();
        int[] redBlackColumns = {6, 8, 10, 12, 14, 16, 18, 20, 22};
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                // 遍历相关列
                for (int j : redBlackColumns) { // redBlackColumns是红黑列的索引数组
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        String cellValue = cell.getStringCellValue();
                        if (Arrays.asList("黑", "0:0").contains(cellValue)) {
                            CellStyle style = writer.getWorkbook().createCellStyle();
                            Font font = writer.getWorkbook().createFont();
                            font.setColor(Font.COLOR_RED);
                            style.setFont(font);
                            style.setAlignment(HorizontalAlignment.CENTER);
                            cell.setCellStyle(style);
                        }
                    }
                }
            }
        }
        // 关闭流
        writer.close();
        writer2.close();
    }
}
